import 'dart:async';

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:qgchat/common/global/global.dart';

class KeepLive extends StatefulWidget {
  final Widget child;

  KeepLive({this.child, Key key}) : super(key: key);

  @override
  _KeepLiveState createState() => _KeepLiveState();
}

class _KeepLiveState extends State<KeepLive> with WidgetsBindingObserver {
  /// 播放静态资源音频类
  AudioCache _player = AudioCache(prefix: 'audio/');

  /// 音频地址
  final String path = 'message.mp3';

  /// 音频实例
  AudioPlayer _audio;

  int badge = 1;
  Timer timer;

  @override
  void initState() {
    super.initState();
    if (mounted) {
      WidgetsBinding.instance.addObserver(this); // 监听app状态

      // _player.load(path);
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (AppLifecycleState.paused == state) {
      log('后台，放歌');
      timer = Timer.periodic(Duration(seconds: 1), (timer) {
        badge++;
        MobpushPlugin.setBadge(badge);
      });
      _player.loop(path).then((res) {
        _audio = res;
      });
    } else {
      log('前台，停歌');
      timer?.cancel();
      _audio?.stop();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // 销毁监听app状态
    _audio?.stop();
    _player.clearCache();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: widget.child,
    );
  }
}
